/**
 * 
 */
package com.net.web.controllers;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.net.domain.AttendanceStatus;
import com.net.domain.ClassHours;
import com.net.domain.ClassInfo;
import com.net.domain.Course;
import com.net.domain.Staff;
import com.net.domain.Student;
import com.net.domain.StudentAttendanceDetail;
import com.net.domain.Subject;
import com.net.service.AttendanceService;
import com.net.service.UtilService;
import com.net.web.form.AttendanceSearchForm;

/**
 * @author Dinesh
 *
 */
public class AttendanceActionController extends MultiActionController {
	
	final static Logger log = Logger.getLogger(AttendanceActionController.class);
	
	final static SimpleDateFormat formatter = new SimpleDateFormat("MM/d/yyyy");
	
	private static int sequenceCounter = 0;
	
	private static HashMap<Integer, List<StudentAttendanceDetail>> cacheForStudentList = new HashMap<Integer, List<StudentAttendanceDetail>>();
	
	private AttendanceService attendanceService;
	
	private UtilService utilService;
	
	public ModelAndView enterAttendanceOthersForm(HttpServletRequest req, HttpServletResponse res) {
		ModelAndView mav = new ModelAndView("enterAttendanceothers");
		
		List<Course> courseList = utilService.getAllCourse();
		mav.addObject("courses", courseList);
		List<Subject> subjectList = utilService.getAllSubject();
		mav.addObject("subjects", subjectList);
		List<ClassInfo> classList = utilService.getAllClass();
		mav.addObject("classes", classList);
		mav.addObject("hours", utilService.getAllClassHours());
		mav.addObject("date", formatter.format(new Date()));
		
		return mav;	
	}
	
	
	public ModelAndView enterAttendanceForm(HttpServletRequest req, HttpServletResponse res) {
		ModelAndView mav = new ModelAndView("enterAttendance");
						
		Staff staff = (Staff)req.getSession().getAttribute("user");
			
		mav.addObject("hours", utilService.getAllClassHours());
		mav.addObject("date", formatter.format(new Date()));
		mav.addObject("classMaps", utilService.getClassByStaff(staff.getStaffId()));
		
		return mav;		
	}
	
	public ModelAndView reportStudentAttendanceForm(HttpServletRequest req, HttpServletResponse res) {
		ModelAndView mav = new ModelAndView("studentReportAttendance");
		log.info("Form called...");
		List<ClassHours> classHourIdList=utilService.getAllClassHours();
				List<Subject> subjectList = utilService.getAllSubject();
		mav.addObject("subjects", subjectList);
		
		
		mav.addObject("startDate", formatter.format(new Date()));
		mav.addObject("endDate", formatter.format(new Date()));
		mav.addObject("classHourIds",classHourIdList);
		
		return mav;	
	}

	
	public ModelAndView displayAttendanceForm(HttpServletRequest req, HttpServletResponse res) {
		ModelAndView mav = new ModelAndView("displayAttendance");
		
		log.info("got into this");
		
		AttendanceSearchForm searchQuery = new AttendanceSearchForm();

		Date date = null;
		
		try {
			date = formatter.parse(req.getParameter("date"));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int classHourId = Integer.parseInt(req.getParameter("class_hour"));
		
		searchQuery.setClassHourId(classHourId);
		searchQuery.setDate(date);
		
		if(req.getParameter("type").equalsIgnoreCase("any")) {
			String combinedClass = req.getParameter("class");
			String [] classSem = combinedClass.split("-");
			
			searchQuery.setSemester(classSem[0]);
			searchQuery.setSectionName(classSem[1]);
			searchQuery.setCouseShortCode(req.getParameter("course"));
			searchQuery.setSubjectCode(req.getParameter("subject"));
		}
		else {
			searchQuery.setSubjectClassGroupId(Integer.parseInt(req.getParameter("class_map")));
		}
				
		List<StudentAttendanceDetail> attendanceList = attendanceService.getAllEligibleStudents(searchQuery);
		
		int key = getSequence();
		
		if(attendanceList.size() > 0) {
			//StudentAttendanceDetail studentanceDetail = attendanceList.get(0);
			log.info("attendance");
			cacheForStudentList.put(key, attendanceList);
		}
		
		mav.addObject("class_hour", classHourId);
		mav.addObject("date", formatter.format(date));
		mav.addObject("randomkey", key);
		mav.addObject("students", attendanceList);
		
		return mav;
	}
	
	private static int getSequence() {
		return sequenceCounter++;
	}
	
	public ModelAndView generateAttendanceStatusForm(HttpServletRequest req, HttpServletResponse res) {
		ModelAndView mav = new ModelAndView("displayAttendanceStatus");
		
		log.info("got into this");
		
		Student student =(Student) req.getSession().getAttribute("user");
		List<StudentAttendanceDetail> attendanceStatusList = null;
		
		
		try {
			Date startDate = formatter.parse(req.getParameter("start_date"));
			Date endDate = formatter.parse(req.getParameter("end_date"));
			
			attendanceStatusList = attendanceService.getAttendanceStatus(student,startDate,endDate);			
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		mav.addObject("students",attendanceStatusList);
				
		return mav;
	}
	

	public ModelAndView writeAttendanceForm(HttpServletRequest req, HttpServletResponse res) throws Exception {

		
		//"course"
			//	"subject"
	//"class" 
	//
		
		// subject id,  class_group_id , student_id
		Date date = formatter.parse(req.getParameter("date"));
		int classHour = Integer.parseInt(req.getParameter("class_hour"));
		int sequence = Integer.parseInt(req.getParameter("randomkey"));
		
		//int classHourMapId = utilService.getClassHourId(classHour);; 
				
		List<StudentAttendanceDetail> attendanceList = cacheForStudentList.get(sequence);
		
		log.info("The sequence " + sequence +classHour+date.toString()+" --> "+attendanceList.size());
		
		if(attendanceList != null)
			cacheForStudentList.remove(sequence);
		
		for(StudentAttendanceDetail studentDetail: attendanceList) {
			
			//TODO: CHeck whether class_hour_mapping is required
			studentDetail.setClassHourMappingId(classHour);
			studentDetail.setDate(date);
			
			String status = req.getParameter("status_" + studentDetail.getStudentId());
			
			log.info("Status is " + status);
			
			AttendanceStatus attendanceStatus = AttendanceStatus.PRESENT;
			
			if(status.equalsIgnoreCase(AttendanceStatus.PRESENT.getValue()))
				attendanceStatus = AttendanceStatus.PRESENT;
			else if(status.equalsIgnoreCase(AttendanceStatus.ABSENT.getValue()))
				attendanceStatus = AttendanceStatus.ABSENT;
			else if(status.equalsIgnoreCase(AttendanceStatus.ONDUTY.getValue()))
				attendanceStatus =  AttendanceStatus.ONDUTY;
			
			studentDetail.setAttendanceStatus(attendanceStatus);
		}
		
		// Write back to the database
		attendanceService.insertAttendanceDetails(attendanceList);
		
		return enterAttendanceForm(req, res);
	}
	
	public UtilService getUtilService() {
		return utilService;
	}
	
	@Autowired
	public void setUtilService(UtilService utilService) {
		this.utilService = utilService;
	}

	public AttendanceService getAttendanceService() {
		return attendanceService;
	}

	@Autowired
	public void setAttendanceService(AttendanceService attendanceService) {
		this.attendanceService = attendanceService;
	}
}
